import {
  createRouter,
  createWebHistory,
  NavigationGuardNext,
  RouteLocationNormalized,
  RouteRecordRaw,
} from "vue-router";
import Login from "@/views/login/Login.vue";
import BaseTemplate from "@/components/layout/BaseTemplate.vue";
import systemRoute from "@/router/systemRoute";
import salesRoute from "@/router/salesRoute";
import technologyRoute from "@/router/technologyRoute";
import qualityRoute from "@/router/qualityRoute";
import purchasingRoute from "@/router/purchasingRoute";
import financeRoute from "@/router/financeRoute";
import supplyRoute from "@/router/supplyRoute";
import productionRoute from "@/router/productionRoute";

const baseRoutes: Array<RouteRecordRaw> = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/login",
    name: "Login",
    component: Login,
  },
  {
    path: "/",
    name: "BaseTemplate",
    component: BaseTemplate,
    children: [
      {
        path: "/home",
        name: "Home",
        component: () =>
          import(/* webpackChunkName: "home" */ "@/views/Home.vue"),
        meta: {
          title: "首页",
        },
      },
    ],
  },
  {
    path: "/about",
    name: "About",
    // route level code-splitting
    // this generates a separate chunk (about.[hash].js) for this route
    // which is lazy-loaded when the route is visited.
    component: () =>
      import(/* webpackChunkName: "about" */ "@/views/About.vue"),
  },
];

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes: baseRoutes
    .concat(systemRoute)
    .concat(salesRoute)
    .concat(technologyRoute)
    .concat(qualityRoute)
    .concat(purchasingRoute)
    .concat(financeRoute)
    .concat(supplyRoute)
    .concat(productionRoute),
});

// 路由守卫, 拦截路由, 判断是否登录.
router.beforeEach(
  (
    to: RouteLocationNormalized,
    from: RouteLocationNormalized,
    next: NavigationGuardNext
  ) => {
    if (to.name !== "Login" && !sessionStorage.getItem("token"))
      next({ name: "Login" });
    else next();
  }
);

export default router;
